package cn.itcast;

import java.util.*;

public class ListTest {

    public static void main(String[] args) {
        List<String> list1= Arrays.asList("a","b","c","e","d","e","e","a");
        ArrayList<String> alist=new ArrayList<>(list1);
        removeDuplicate(alist);

        alist.forEach(System.out::println);

        final List<String> list = new ArrayList<String>();
        for (int i = 0; i < 1000; i++) {
            list.add("haha-" + i);
        }

        long time = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            removeDuplicate(list);
        }
        long time1 = System.currentTimeMillis();
        System.out.println("time1:"+(time1-time));

        for (int i = 0; i < 10000; i++) {
            removeDuplicate1(list);
        }
        long time2 = System.currentTimeMillis();
        System.out.println("time2:"+(time2-time1));

        for (int i = 0; i < 10000; i++) {
            removeDuplicat2(list);
        }
        long time3 = System.currentTimeMillis();
        System.out.println("time3:"+(time3-time2));

    }
    //方式一，利用HashSet不能添加重复数据的特性 由于HashSet不能保证添加顺序，所以只能作为判断条件：
    private static void removeDuplicate(List<String> list) {
        HashSet<String> set = new HashSet<String>(list.size());
        List<String> result = new ArrayList<String>(list.size());
        for (String str : list) {
            if (set.add(str)) {
                result.add(str);
            }
        }
        list.clear();
        list.addAll(result);
    }


    private static void removeDuplicate1(List<String> list) {
        LinkedHashSet<String> set = new LinkedHashSet<String>(list.size());
        set.addAll(list);
        list.clear();
        list.addAll(set);
    }

    private static void removeDuplicat2(List<String> list) {
        List<String> result = new ArrayList<String>(list.size());
        for (String str : list) {
            if (!result.contains(str)) {
                result.add(str);
            }
        }
        list.clear();
        list.addAll(result);
    }


}
